package com.wcl.nullmusic.ui.service;

import android.app.ActivityManager;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Binder;
import android.os.IBinder;
import android.os.RemoteException;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.util.Log;
import android.widget.RemoteViews;

import com.android.volley.Response;
import com.google.gson.Gson;
import com.squareup.picasso.Picasso;
import com.wcl.nullmusic.Mp3Info;
import com.wcl.nullmusic.R;
import com.wcl.nullmusic.base.BaseAppcation;
import com.wcl.nullmusic.mode.AnthologyResult;
import com.wcl.nullmusic.mode.Anthology_Track_List;
import com.wcl.nullmusic.mode.PlayMusic;
import com.wcl.nullmusic.ui.activity.MainActivity;
import com.wcl.nullmusic.utils.BaseUtils;
import com.wcl.nullmusic.utils.LocalMp3InfoUtils;
import com.wcl.nullmusic.utils.VolleyUtils;

import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.Random;

import de.greenrobot.event.EventBus;

/**
 * Created by dllo on 16/1/21.
 */
public class NullMusicService extends Service implements MediaPlayer.OnCompletionListener, MediaPlayer.OnErrorListener, MediaPlayer.OnPreparedListener {

    public static final int PLAYER_PLAY = 110; // 播放
    public static final int PLAYER_PAUSE = 120; // 暂停
    public static final int PLAYER_START = 130; // 继续播放
    public static final int PLAYER_PREV = 140; // 上一首
    public static final int PLAYER_NEXT = 150; // 下一首
    public static final int OBTIAN_MUSIC_CURRENTPOSITION = 210; // 获取当前音乐播放进度
    public static final int SEND_MUSIC_CURRENTPOSITION = 211; // 发送当前音乐播放进度
    public static final int CHANGE_MUSIC_CURRENTPOSITION = 212; // 改变当前音乐播放进度
    public static final int OBTIAN_MUSIC_PLAYERMODE = 220; // 获取音乐播放模式
    public static final int SEND_MUSIC_PLAYERMODE = 221; // 发送音乐播放模式
    public static final int CHANGE_MUSIC_PLAYERMODE = 222; // 改变音乐播放模式
    public static final int OBTIAN_MUSIC_ISPLAYING = 230; // 获取当前音乐播放状态
    public static final int SEND_MUSIC_ISPLAYING = 231; // 发送当前音乐播放状态
    public static final int OBTIAN_MUSIC_DURATION = 240; // 获取当前音乐时长
    public static final int SEND_MUSIC_DURATION = 241; // 发送当前音乐时长
    public static final int OBTAIN_MUSIC_ALLINFO = 310; // 获取音乐所有信息
    public static final int SEND_MUSIC_ALLINFO = 311; // 发送音乐所有信息
    public static final int OBTAIN_MUSIC_POSITION = 410; // 获取本地音乐位置
    public static final int SEND_MUSIC_POSITION = 411; // 发送本地音乐位置

    private PlayMusic playMusic;

    public static final int PLAYER_MODE_ORDER = 0; // 顺序播放
    public static final int PLAYER_MODE_SINGLE = 1; // 单曲播放
    public static final int PLAYER_MODE_RANDOM = 2; // 随机播放
    private int play_mode = PLAYER_MODE_ORDER;
    private boolean isFirst = true;
    private boolean flag = false; // false为本地播放 true为网络播放
    private MediaPlayer player;

    private List<Mp3Info> mp3Infolist; //本地音乐数据集合
    private List<Anthology_Track_List> datas; //网络音乐数据集合
    private Mp3Info mp3Info = new Mp3Info(); //音乐数据

    private int currentPosition = 0;// 记录音乐播放的位置
    private int musicItemPosition = 0;
    private int seekbarProgress; // seekbar进度条
    private int musicPosition; // 记录本地音乐播放位置
    public static final String PLAY_ACTION = "com.wcl.nullmusic.NOTIFICATION_PLAY";
    public static final String NEXT_ACTION = "com.wcl.nullmusic.NOTIFICATION_NEXT";
    public static final String PREV_ACTION = "com.wcl.nullmusic.NOTIFICATION_PREV";
    public static final String EXIT_ACTION = "com.wcl.nullmusic.NOTIFICATION_EXIT";
    public static final String UPDATE_ACTION = "com.wcl.nullmusic.NOTIFICATION_UPDATE";

    private PlayerBinder binder;
    private NotificationReceiver notificationReceiver = new NotificationReceiver();
    private String notification_msg;
    private NotificationManager notificationManager;

    private Random random = new Random(); // 随机数,随机播放模式


    @Override
    public void onCreate() {
        super.onCreate();
        this.binder = new PlayerBinder();
        this.player = new MediaPlayer();
        EventBus.getDefault().register(this);
        player.setOnCompletionListener(this);
        player.setOnErrorListener(this);
        player.setOnPreparedListener(this);
        this.mp3Infolist = LocalMp3InfoUtils.getMp3Info();
        SharedPreferences sp = BaseAppcation.sp;

        play_mode = sp.getInt("play_mode", PLAYER_MODE_ORDER);
        currentPosition = sp.getInt("currentPosition", 0);

        seekbarProgress = sp.getInt("seekbarProgress", 0);
        mp3Info = mp3Infolist.get(currentPosition);
        EventBus.getDefault().post(mp3Info);
//        playMusic=new PlayMusic();
//        playMusic.setPosition(musicPosition);
//        playMusic.setCurrentPosition(seekbarProgress);
//        playMusic.set
//        EventBus.getDefault().post();
        initNotification(notificationManager);
        registerRecevier();

    }

    public void onEvent(Integer requestCode) {
        Log.i("onEvent", "service onEvent(Integer requestCode)");
        switch (requestCode) {
            case PLAYER_PLAY:
                break;
            case PLAYER_PAUSE:
                pause();
//                playMusic.setState(SEND_MUSIC_ISPLAYING);
//                playMusic.setCurrentIsPlaying(isPlaying());
//                EventBus.getDefault().post(playMusic);
                break;
            case PLAYER_START:
                start();
//                playMusic.setState(SEND_MUSIC_ISPLAYING);
//                playMusic.setCurrentIsPlaying(isPlaying());
//                EventBus.getDefault().post(playMusic);
                break;
            case PLAYER_PREV:
                prev();
                break;
            case PLAYER_NEXT:
                next();
                break;
            case OBTIAN_MUSIC_CURRENTPOSITION:
                playMusic = new PlayMusic();
                playMusic.setState(SEND_MUSIC_CURRENTPOSITION);
                playMusic.setCurrentPosition(currentPosition());
                EventBus.getDefault().post(playMusic);
                break;

            case OBTIAN_MUSIC_PLAYERMODE:
                playMusic = new PlayMusic();
                playMusic.setState(SEND_MUSIC_PLAYERMODE);
                playMusic.setCurrentPlayMode(playMode());
                EventBus.getDefault().post(playMusic);
                break;

            case OBTIAN_MUSIC_ISPLAYING:
                playMusic = new PlayMusic();
                playMusic.setState(SEND_MUSIC_ISPLAYING);
                playMusic.setCurrentIsPlaying(isPlaying());
                EventBus.getDefault().post(playMusic);
                break;
            case OBTIAN_MUSIC_DURATION:
                playMusic = new PlayMusic();
                playMusic.setState(SEND_MUSIC_DURATION);
                playMusic.setCurrentDuration(duration());
                EventBus.getDefault().post(playMusic);
                break;
            case OBTAIN_MUSIC_ALLINFO:
                playMusic = new PlayMusic();
                playMusic.setState(SEND_MUSIC_ALLINFO);
                playMusic.setCurrentPosition(duration());
                playMusic.setCurrentDuration(currentPosition());
                playMusic.setCurrentPlayMode(playMode());
                playMusic.setCurrentIsPlaying(isPlaying());
                EventBus.getDefault().post(playMusic);
                EventBus.getDefault().post(mp3Info);
                break;
            case OBTAIN_MUSIC_POSITION:
                playMusic = new PlayMusic();
                playMusic.setState(SEND_MUSIC_POSITION);
                playMusic.setMusicPosition(getPosition());
                EventBus.getDefault().post(playMusic);
                break;


        }
    }

    public void onEvent(PlayMusic playMusic) {
        Log.i("onEvent", "service onEvent(PlayMusic playMusic)");
        int state = playMusic.getState();
        switch (state) {
            case PLAYER_PLAY:
                currentPosition = playMusic.getPosition();
                flag = playMusic.isFlag();
                if (flag) {
                    String url = playMusic.getUrl();
                    onlinePlay(url, currentPosition);
                } else {
                    if (currentPosition < 0) {
                        currentPosition = musicItemPosition;
                        play(musicItemPosition, flag);
                        player.seekTo(seekbarProgress);
                    } else
                        play(currentPosition, flag);
                }
                break;
            case CHANGE_MUSIC_CURRENTPOSITION:
                seekTo(playMusic.getCurrentPosition());
                break;
            case CHANGE_MUSIC_PLAYERMODE:
                chagePlayMode(playMusic.getChangePlayerMode());
                Log.i("kl", "设置播放模式  " + playMusic.getChangePlayerMode());
//                playMusic = new PlayMusic();
//                playMusic.setState(SEND_MUSIC_PLAYERMODE);
//                playMusic.setCurrentPlayMode(playMode());
//                EventBus.getDefault().post(playMusic);
                break;
        }
    }

    /**
     * 播放
     *
     * @param position
     * @param b
     */
    public void play(int position, boolean b) {
        if (b) {
            if (position >= 0 && position < datas.size()) {
                try {
                    Anthology_Track_List list = datas.get(position);
                    player.reset();
                    player.setDataSource(this, Uri.parse(list.getPlayUrl64()));
                    //  player.prepare();
                    player.prepareAsync();


                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        } else {
            if (position >= 0 && position < mp3Infolist.size()) {
                mp3Info = mp3Infolist.get(position);
                try {
                    // flag = false;
                    player.reset();
                    player.setDataSource(this, Uri.parse(mp3Info.getUrl()));
                    // player.prepare();
                    player.prepareAsync();
//                    if (isFirst && isFirst && !player.isPlaying()) {
//                        player.seekTo(seekbarProgress);
//                        seekbarProgress = 0;
//                        isFirst = false;
//                    }
//                        player.start();

                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        currentPosition = position;

    }

    // 暂停
    public void pause() {
        if (player.isPlaying()) {
            player.pause();
            initNotification(notificationManager);
        }
    }

    // 继续播放
    public void start() {
        if (!player.isPlaying() && player != null) {
            // player.prepareAsync();
            player.start();
        }
    }

    // 上一首
    public void prev() {
        switch (play_mode) {
            case PLAYER_MODE_ORDER:

                if (flag)
                    if (currentPosition == 0)
                        play(datas.size() - 1, flag);
                    else
                        play(currentPosition + 1, flag);
                else {
                    if (currentPosition == 0)
                        play(mp3Infolist.size() - 1, flag);
                    else
                        play(currentPosition + 1, flag);
                }

                break;
            case PLAYER_MODE_SINGLE:
                play(currentPosition, flag);
                break;
            case PLAYER_MODE_RANDOM:
                if (flag)
                    play(random.nextInt(datas.size()), flag);
                else
                    play(random.nextInt(mp3Infolist.size()), flag);
                break;
        }
    }

    // 下一首
    public void next() {
        isFirst = false;
        switch (play_mode) {
            case PLAYER_MODE_ORDER:
                if (flag)
                    if (currentPosition == datas.size() - 1)
                        play(0, flag);
                    else
                        play(currentPosition + 1, flag);
                else {
                    if (currentPosition == mp3Infolist.size() - 1)
                        play(0, flag);
                    else
                        play(currentPosition + 1, flag);
                }

                break;
            case PLAYER_MODE_SINGLE:
                play(currentPosition, flag);
                break;
            case PLAYER_MODE_RANDOM:
                if (flag)
                    play(random.nextInt(datas.size()), flag);
                else
                    play(random.nextInt(mp3Infolist.size()), flag);
                break;
        }
    }

    // 是否正在播放
    public boolean isPlaying() {
        return player.isPlaying();
    }

    // 当前音乐的进度
    public int currentPosition() {
        return player.getCurrentPosition();
    }

    // 改变播放模式
    public void chagePlayMode(int mode) {
        play_mode = mode;
    }

    // 获取当前的播放模式
    public int playMode() {
        return play_mode;
    }

    // 当前音乐的总时长
    public int duration() {
        return player.getDuration();
    }

    // 调整音乐的进度
    public void seekTo(int pro) {
        player.seekTo(pro);
    }

    // 获取seekbar进度
    public int seekbarProgress() {
        return seekbarProgress;
    }

    // 获得本地音乐播放位置
    public int getPosition() {
        return musicPosition;
    }

    // 是否是第一次播放

    public boolean isFirst() {
        return isFirst;
    }

    // 设置音乐信息
    public Mp3Info getMp3Info() {
        if (flag)
            return mp3Info;
        return mp3Infolist.get(currentPosition);
    }

    // 获取在线播放音乐列表
    public void onlinePlay(String url, final int pos) {
        VolleyUtils.getInstance().StringRequest(url, new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                Log.i("music", response + "<++++");
                Gson gson = new Gson();
                AnthologyResult result = gson.fromJson(response, AnthologyResult.class);
                datas = result.getTracks().getList();
                flag = true;
                play(pos, flag);
            }
        }, "Music_StingRequest");

    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
//        if (binder != null)
        new Thread(new Runnable() {
            @Override
            public void run() {
                while (true) {
                    if (player != null && player.isPlaying()) {
                        try {
                            Thread.sleep(300);
                            playMusic = new PlayMusic();
                            playMusic.setState(SEND_MUSIC_CURRENTPOSITION);
                            playMusic.setCurrentPosition(currentPosition());
                            EventBus.getDefault().post(playMusic);

                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                }
            }
        }).start();
        //  return super.onStartCommand(intent, flags, startId);
        return super.onStartCommand(intent, Service.START_REDELIVER_INTENT, startId);
    }

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return binder;
    }


    @Override
    public void onCompletion(MediaPlayer mp) {
        switch (play_mode) {
            case PLAYER_MODE_ORDER:
                next();
                break;
            case PLAYER_MODE_SINGLE:
                play(currentPosition, flag);
                break;
            case PLAYER_MODE_RANDOM:
                play(random.nextInt(mp3Infolist.size()), flag);
                break;
        }
    }

    @Override
    public boolean onError(MediaPlayer mp, int what, int extra) {
        player.reset();
        return false;
    }

    @Override
    public void onPrepared(MediaPlayer mp) {
        mp.start();
        if (flag) {
            Anthology_Track_List list = datas.get(currentPosition);
            mp3Info = new Mp3Info();
            mp3Info.setArtist(list.getNickname());
            mp3Info.setTitle(list.getTitle());
            mp3Info.setPic(list.getCoverLarge());
            mp3Info.setDuration(mp.getDuration());
        }
        EventBus.getDefault().post(mp3Info);
        initNotification(notificationManager);

        playMusic = new PlayMusic();
        playMusic.setState(SEND_MUSIC_POSITION);
        playMusic.setMusicPosition(currentPosition);
        EventBus.getDefault().post(playMusic);

    }

    public class PlayerBinder extends Binder {

    }

    private void initNotification(NotificationManager manager) {
        manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
        if (!flag)
            mp3Info = mp3Infolist.get(currentPosition);
        Notification notification = new Notification(R.mipmap.null_64, "NullMusic", System.currentTimeMillis());
        RemoteViews remoteViews = new RemoteViews(BaseAppcation.getContext().getPackageName(), R.layout.notification);
        if (player.isPlaying())
            remoteViews.setImageViewResource(R.id.notification_player, R.mipmap.bt_lockscreen_pause_press);
        else
            remoteViews.setImageViewResource(R.id.notification_player, R.mipmap.bt_lockscreen_play_press);
        // 音乐图片
        String picUrl = mp3Info.getUrl();
        if (flag)
            Picasso.with(this).load(mp3Info.getPic()).into(remoteViews, R.id.notification_pic, 3, notification);
        else {
            if (!TextUtils.isEmpty(picUrl)) {
                BitmapFactory.Options options = new BitmapFactory.Options();
                options.inPreferredConfig = Bitmap.Config.RGB_565;
                Bitmap bitmap = BitmapFactory.decodeFile(mp3Info.getPic(), options);
                remoteViews.setImageViewBitmap(R.id.notification_pic, bitmap);
            } else
                remoteViews.setImageViewResource(R.id.notification_pic, R.mipmap.ic_live_voice_press);
        }
        // 音乐名称和歌手
        remoteViews.setTextViewText(R.id.notification_desc, mp3Info.getTitle() + " " + mp3Info.getArtist());

        Intent notificationIntent = new Intent(this, MainActivity.class);
        PendingIntent contentIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);


        // 上一首
        remoteViews.setOnClickPendingIntent(R.id.notification_prev, action_pendingIntent(PREV_ACTION));
        // 播放or暂停
        remoteViews.setOnClickPendingIntent(R.id.notification_player, action_pendingIntent(PLAY_ACTION));
        // 下一首
        remoteViews.setOnClickPendingIntent(R.id.notification_next, action_pendingIntent(NEXT_ACTION));


        notification.contentIntent = contentIntent;


        // 将内容指定给通知
        notification.contentView = remoteViews;
        // 指定点击后调到Activity
        //   notification.contentIntent = PendingIntent.getActivity(BaseAppcation.getContext(), 0, new Intent(BaseAppcation.getContext(), MainActivity.class), PendingIntent.FLAG_UPDATE_CURRENT);
        // 指定通知可以清除
        //    notification.flags |=Notification.FLAG_AUTO_CANCEL;
        // 指定通知不能清除
        notification.flags = Notification.FLAG_NO_CLEAR;
        // 通知显示的时候播放默认背光
        //  notification.flags |= Notification.FLAG_SHOW_LIGHTS;
        // 向NotificationManager注册一个notification，并用NOTIFICATION_ID作为管理的唯一标示

        manager.notify(3, notification);

    }

    public PendingIntent action_pendingIntent(String action) {
        Intent intent = new Intent(action);
        PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
        return pendingIntent;
    }

    public void registerRecevier() {

        IntentFilter play_intentFilter = new IntentFilter();
        IntentFilter next_intentFilter = new IntentFilter();
        IntentFilter prev_intentFilter = new IntentFilter();
        IntentFilter exit_intentFilter = new IntentFilter();
        play_intentFilter.addAction(PLAY_ACTION);
        next_intentFilter.addAction(NEXT_ACTION);
        prev_intentFilter.addAction(PREV_ACTION);
        exit_intentFilter.addAction(EXIT_ACTION);
        registerReceiver(notificationReceiver, play_intentFilter);
        registerReceiver(notificationReceiver, next_intentFilter);
        registerReceiver(notificationReceiver, prev_intentFilter);
        registerReceiver(notificationReceiver, exit_intentFilter);
    }

    class NotificationReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {

            Boolean notification_previous_music = false;
            Boolean notification_next_music = false;
            Boolean notification_pause_music = false;
            Boolean notification_exit = false;

            notification_msg = intent.getAction();
            if (notification_msg.equals(PLAY_ACTION)) {
                if (player.isPlaying())
                    pause();
                else {
                    start();
                }
                initNotification(notificationManager);
            } else if (notification_msg.equals(NEXT_ACTION)) {
                next();
                initNotification(notificationManager);
            } else if (notification_msg.equals(PREV_ACTION)) {
                prev();
                initNotification(notificationManager);
            } else if (notification_msg.equals(EXIT_ACTION)) {
                notificationManager.cancelAll();
                player.stop();
                player.release();
                player = null;
                stopSelf();
                BaseAppcation.getInstance().finishAllActivity();
                BaseAppcation.getInstance().AppExit();
                //    am.restartPackage(getPackageName());

//                Log.d("taggg", "onReceive() called with: " + "context = [" + context + "], intent = [" + intent + "]");
//                player.stop();
//                player.release();
//                player = null;
//                notificationManager.cancelAll();
//                BaseAppcation.removeAllActivity();
//                stopSelf();
//                    System.exit(0);
//                } catch (Exception e) {
//                    e.printStackTrace();
//                }
//                return;
            }
            //   initNotification(notificationManager);
        }
    }

    @Override
    public void onDestroy() {
        Log.i("test", "--Service onDestroy--");
        if (player != null) {
            if (player.isPlaying()) {
                player.stop();
            }
            player.release();
            player = null;
        }
        EventBus.getDefault().unregister(this);
        unregisterReceiver(notificationReceiver);
        super.onDestroy();
    }
}
